import {
  ModalForm,
  ProForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Form, message } from 'antd';
import { useEffect } from 'react';

import { addMaterial, updateMaterial } from '@/services/materialManageApi';
import { getCategoryList, getLocationList } from '@/services/categoryLocationApi';

interface EditDrawerProps {
  open: boolean;
  record: MATERIAL.MaterialModel | null;
  onFinish: () => void;
  onCancel: () => void;
}

/**
 * 物资编辑抽屉
 */
export default function MaterialEditDrawer(props: EditDrawerProps) {
  const { open, record, onFinish, onCancel } = props;
  const [form] = Form.useForm();
  const isEdit = !!record;

  // 重置表单
  useEffect(() => {
    if (open) {
      if (record) {
        form.setFieldsValue(record);
      } else {
        form.resetFields();
      }
    }
  }, [open, record, form]);

  // 添加物资请求
  const addRequest = useRequest(addMaterial, {
    manual: true,
    onSuccess: () => {
      message.success('添加成功');
      onFinish();
    },
  });

  // 更新物资请求
  const updateRequest = useRequest(updateMaterial, {
    manual: true,
    onSuccess: () => {
      message.success('更新成功');
      onFinish();
    },
  });

  // 提交表单
  const handleSubmit = async (values: any) => {
    // 根据库存数量与最低库存比较自动计算状态
    let status = '正常';
    
    if (values.status === '已报废') {
      status = '已报废';
    } else if (values.quantity === 0) {
      status = '待补充';
    } else if (values.quantity <= values.minQuantity) {
      status = '不足';
    }
    
    const submitData = {
      ...values,
      status,
    };
    
    if (isEdit && record) {
      // 更新物资
      await updateRequest.run({
        ...submitData,
        id: record.id,
      });
    } else {
      // 添加物资
      await addRequest.run(submitData);
    }
  };

  return (
    <ModalForm
      title={isEdit ? '编辑物资' : '新增物资'}
      form={form}
      open={open}
      onFinish={handleSubmit}
      onOpenChange={(visible) => {
        if (!visible) {
          onCancel();
        }
      }}
      submitter={{
        searchConfig: {
          submitText: isEdit ? '更新' : '提交',
        },
        resetButtonProps: {
          style: {
            display: 'none',
          },
        },
      }}
    >
      <ProForm.Group>
        <ProFormText
          name="materialName"
          label="物资名称"
          width="md"
          rules={[{ required: true, message: '请输入物资名称' }]}
        />
        <ProFormText
          name="specification"
          label="规格型号"
          width="md"
          rules={[{ required: true, message: '请输入规格型号' }]}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormDigit
          name="quantity"
          label="库存数量"
          width="md"
          min={0}
          rules={[{ required: true, message: '请输入库存数量' }]}
        />
        <ProFormText
          name="unit"
          label="单位"
          width="md"
          rules={[{ required: true, message: '请输入单位' }]}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormDigit
          name="minQuantity"
          label="最低库存"
          width="md"
          min={0}
          rules={[{ required: true, message: '请输入最低库存' }]}
        />
        <ProFormSelect
          name="categoryId"
          label="物资分类"
          width="md"
          rules={[{ required: true, message: '请选择物资分类' }]}
          request={async () => {
            try {
              const res = await getCategoryList();
              if (res.code === 200 && Array.isArray(res.data)) {
                return res.data.map((item: CATEGORY.CategoryModel) => ({
                  label: item.name,
                  value: item.id,
                }));
              }
              return [];
            } catch (error) {
              console.error('获取物资分类失败', error);
              return [];
            }
          }}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormSelect
          name="locationId"
          label="存放位置"
          width="md"
          rules={[{ required: true, message: '请选择存放位置' }]}
          request={async () => {
            try {
              const res = await getLocationList();
              if (res.code === 200 && Array.isArray(res.data)) {
                return res.data.map((item: LOCATION.LocationModel) => ({
                  label: item.locationName,
                  value: item.id,
                }));
              }
              return [];
            } catch (error) {
              console.error('获取存放位置失败', error);
              return [];
            }
          }}
        />
        <ProFormText
          name="responsiblePerson"
          label="负责人"
          width="md"
        />
      </ProForm.Group>

      <ProFormSelect
        name="status"
        label="特殊状态"
        width="md"
        tooltip="只需在物资报废时选择已报废，其他状态将根据库存数量与最低库存自动判断"
        options={[
          { label: '正常', value: '正常' },
          { label: '已报废', value: '已报废' },
        ]}
      />

      <ProFormTextArea
        name="remarks"
        label="备注"
        width="xl"
      />
    </ModalForm>
  );
}